﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Windows.Interop;
using System.Collections;
using DoubleH.Utility.Configuration;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace POS.Templete.TouchTemplete
{
    /// <summary>
    /// StoreSales.xaml 的交互逻辑
    /// </summary>
    public partial class PageSale : Page, ISaleTemplete
    {
        private enum EnumMode
        {
            NULL,
            数量,
            价格,
            会员
        }

        public PageSale()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }

        public event dSaleToPayEvent Saled;
        public event dZengSong ZengSong;
        public event dEditProduct EditProduct;
        public event dNoParams JiaoBan;
        public event dGuaDan GuaDan;
        public event dNoParams TuiHuo;
        EnumMode mode = EnumMode.NULL;
        ObservableCollection<Table.ProductS> customProductSList = new ObservableCollection<Table.ProductS>();

        private void InitVar()
        {
            this.Background = App.BackgroundBrush;
            this.Foreground = App.ForegroundBrush;
            foreach (UIElement ui in mainGrid.Children)
            {
                Control c = ui as Control;
                if (c != null)
                {
                    if (c.Name == "buttonSaled"||c.Name=="buttonRemoveRow")//要这样，否则就看不到图片了。
                        continue;

                    c.Background = App.BackgroundBrush;
                    c.Foreground = App.ForegroundBrush;
                }
            }

            productSListInfo1.Background = Brushes.Green;
            productSListInfo1.Foreground = this.Foreground;
            productSListInfo1.ShowBodyContexMenu = false;
            productSListInfo1.ShowAverage = false;
            productSListInfo1.EnableText = string.Empty;
            productSListInfo1.CanUserAddRows = false;
            productSListInfo1.CanSelectProduct = false;
            productSListInfo1.SelectionUnit = DataGridSelectionUnit.FullRow;
            productSListInfo1.ProductSType = ProductS.GetProductS.EnumProductS.可销售商品;

            uCPagePanel1.HideLieBiao = true;
            uCPagePanel1.Background = this.Background;
            uCPagePanel1.Foreground = this.Foreground;
            uCPagePanel1.FontSize = DoubleHConfig.AppConfig.PosProductFontSize;
  
            labelCashboxMoney.Content = DoubleHConfig.AppConfig.PosCashboxMoney;
        }

        private void InitEvent()
        {
            textBoxInput.KeyDown += new KeyEventHandler(textBoxInput_KeyDown);
            uCPagePanel1.ItemDoubleClick += (ee) => UCPagePanelItemDoubleClick(ee);
            buttonSaled.Click += (ss, ee) => SaleToPay();

            buttonQuantity.Click += (ss, ee) => SelectMode(buttonQuantity);
            buttonPrice.Click += (ss, ee) => SelectMode(buttonPrice);
            buttonVIP.Click += (ss, ee) => SelectMode(buttonVIP);
            buttonOK.Click += (ss, ee) => ButtonOKClick();
            button0.Click += (ss, ee) => textBoxInput.AppendText("0");
            button1.Click += (ss, ee) => textBoxInput.AppendText("1");
            button2.Click += (ss, ee) => textBoxInput.AppendText("2");
            button3.Click += (ss, ee) => textBoxInput.AppendText("3");
            button4.Click += (ss, ee) => textBoxInput.AppendText("4");
            button5.Click += (ss, ee) => textBoxInput.AppendText("5");
            button6.Click += (ss, ee) => textBoxInput.AppendText("6");
            button7.Click += (ss, ee) => textBoxInput.AppendText("7");
            button8.Click += (ss, ee) => textBoxInput.AppendText("8");
            button9.Click += (ss, ee) => textBoxInput.AppendText("9");
            buttonDote.Click += (ss, ee) => textBoxInput.AppendText(".");
            buttonDelete.Click += (ss, ee) => textBoxInput.Clear();
            buttonRemoveRow.Click += (ss, ee) => RemoveProduct();

            buttonZengSong.Click += (ss, ee) => ZengSongClick();
            buttonGuaDan.Click += (ss, ee) => GuaDanNow();
            buttonNew.Click += (ss, ee) => NewOrder();
            buttonJiaoBan.Click += (ss, ee) => JiaoBanNow();
            buttonConfig.Click += (ss, ee) => App.SysConfig();
            buttonTuiHuo.Click += (ss, ee) => TuiHuoNow();
            buttonClose.Click += (ss, ee) => App.Close();
            buttonLogoff.Click += (ss, ee) => App.LogOff(true);
        }

        private void textBoxInput_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                ButtonOKClick();
        }

        private void RemoveProduct()
        {
            EditProduct(EnumEditProduct.移除,productSListInfo1.SelectedItem, 1, 0);
        }

        private void InitData()
        {
            uCPagePanel1.LoadData(App.AllGroupS,App.AllProductS);
            if (DoubleHConfig.AppConfig.PosProductSMode == 0)
            {
                if (!string.IsNullOrEmpty(DoubleHConfig.AppConfig.PosCustomProductS))
                {
                    List<Int64> id = new List<long>();
                    foreach (string str in DoubleHConfig.AppConfig.PosCustomProductS.Split(','))
                        id.Add(Int64.Parse(str));

                    customProductSList = Table.ProductS.GetList(id.ToArray()) ?? new ObservableCollection<Table.ProductS>();
                }
                uCPagePanel1.HomeData = customProductSList;
            }
            else
            {
                customProductSList = Table.ProductS.GetListForPos(DoubleHConfig.AppConfig.PosProductSCount);
                uCPagePanel1.HomeData = customProductSList;
            }
        }

        private void SelectMode(Button btn)
        {
            btn.IsEnabled = false;
            mode = (EnumMode)Enum.Parse(typeof(EnumMode), btn.Content.ToString());
        }

        private void SaleToPay()
        {
            if (!productSListInfo1.HasItems)
                return;

            Clear();
            if (Saled != null)
                Saled();
        }

        private void ButtonOKClick()
        {
            Debug.Assert(EditProduct != null);

            switch (mode)
            {
                case EnumMode.会员: GetCorS(textBoxInput.Text, false); break;
                case EnumMode.价格:
                    double d1 = 0;
                    double.TryParse(textBoxInput.Text, out d1);
                    EditProduct(EnumEditProduct.编辑价格, productSListInfo1.SelectedItem, 0,Math.Abs( d1));
                    break;

                case EnumMode.数量:
                    double d2 = 0;
                    double.TryParse(textBoxInput.Text, out d2);
                    if (d2 == 0)
                        d2 = 1;

                    EditProduct(EnumEditProduct.编辑数量, productSListInfo1.SelectedItem, Math.Abs(d2), 0);
                    break;

                default:
                    if (string.IsNullOrEmpty(textBoxInput.Text))
                        break;

                    Table.ProductS product = App.GetProductSBySearch(textBoxInput.Text.Trim());
                    if (product == null)
                        MessageWindow.Show("商品不存在");
                    else
                    {
                        productSListInfo1.InsertItem(0, product);
                        productSListInfo1.SelectedIndex = 0;
                    }
                    if (productSListInfo1.Count > 0)
                        productSListInfo1.SelectedIndex = 0;
                    break;
            }
            Clear();
            textBoxInput.Focus();
        }

        private void Clear()
        {
            mode = EnumMode.NULL;
            buttonQuantity.IsEnabled = true;
            buttonPrice.IsEnabled = true;
            buttonVIP.IsEnabled = true;
            textBoxInput.Clear();
        }

        private void UCPagePanelItemDoubleClick(object ee)
        {
            Debug.Assert(EditProduct != null, "商品编辑事件不能为空");

            Table.ProductS product = ee as Table.ProductS;
            Debug.Assert(product != null);

            product.InitPrice(null);
            //if (productSListInfo1.ItemsSource.Contains(product))
            //    EditProduct(EnumEditProduct.编辑数量, product, product._TempQuantity += 1, 0);
            //else
            //{
                product._TempQuantity = 1; //因为商品全部已经加在到软件中，引用类型的。所以注意数量的编辑哦
                EditProduct(EnumEditProduct.添加, product, 1, 0);
            //}

            productSListInfo1.SelectedIndex = 0;
            if (productSListInfo1.Count > 0)
                productSListInfo1.SelectedIndex = 0;
        }

        private void JiaoBanNow()
        {
            if (JiaoBan != null)
                JiaoBan();
        }

        private void GuaDanNow()
        {
            if (GuaDan == null)
                return;

            if (!string.IsNullOrEmpty(textBoxInput.Text))//取单
                GuaDan(true, false, textBoxInput.Text);
            else
                GuaDan(true, true, null);

            textBoxInput.Clear();
        }

        private void TuiHuoNow()
        {
            if (TuiHuo != null)
                TuiHuo();
        }

        private void ZengSongClick()
        {
            if (ZengSong != null)
                ZengSong();
        }

        private void NewOrder()
        {
            App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
            InitOrder();
        }

        private void GetCorS(string searchText, bool searchInGuaDan)
        {
            Table.CorS corS = App.GetCorSBySearch(searchText, searchInGuaDan,true);
            textBoxInput.Clear();
            if (corS == null)
            {
                labelVipNO.Content = string.Empty;
                labelRemainIntegral.Content = string.Empty;
            }
            else
            {
                labelVipNO.Content = corS.VipNO;
                labelRemainIntegral.Content = corS.VipRemainIntegral;
                App.Order.CorSId = corS.Id;
            }
        }


        public void Init()
        {
            UserUIparams userParams = DoubleHConfig.UserConfig.GetUserUIparams(DataTableText.Pos零售商品编辑);
            userParams.Mode = DoubleH.Utility.UC.UCPagePanel.EnumMode.缩略图;

            productSListInfo1.Init(userParams);
            switch (DoubleHConfig.AppConfig.PosProductShowMode)
            {
                case 1: uCPagePanel1.Init(userParams, DoubleH.Utility.UC.PagePanel.PageListView.EnumModeTemplete.PosProductSItemTemplateNoText); break;
                case 2: uCPagePanel1.Init(userParams, DoubleH.Utility.UC.PagePanel.PageListView.EnumModeTemplete.PosProductSItemTemplateNoImg); break;
                default: uCPagePanel1.Init(userParams, DoubleH.Utility.UC.PagePanel.PageListView.EnumModeTemplete.PosProductSItemTemplate); break;
            }

            buttonGuaDan.IsEnabled = Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.挂单) != Table.UserS.EnumAuthority.无权限;
            buttonConfig.IsEnabled = Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.POS机配置) != Table.UserS.EnumAuthority.无权限;
            buttonTuiHuo.IsEnabled = Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.退货) != Table.UserS.EnumAuthority.无权限;

            InitData();
        }

        public void InitOrder()
        {
            if (App.Order == null)
                return;

            productSListInfo1.ItemsSource = App.Order.ProductSList;
            GetCorS(App.Order.CorSId.ToString(), true); 
        }

        public Table.StoreS StoreS { set { productSListInfo1.StoreS = value; } }

        public void OrderFinish(Table.PosOrderS order) 
        {
            labelCashboxMoney.Content = DoubleHConfig.AppConfig.PosCashboxMoney;
        }

        public void GuaDanFinish(System.Collections.IList guaDanList) { }
    }
}